<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品数据调试工具</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            max-width: 1200px; 
            margin: 0 auto; 
            padding: 20px; 
            background: #f5f5f5;
        }
        .container { 
            background: white; 
            padding: 25px; 
            border-radius: 8px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .section { 
            margin: 20px 0; 
            padding: 15px; 
            border: 1px solid #ddd; 
            border-radius: 5px; 
        }
        .error { background: #fee; border-color: #fcc; }
        .success { background: #efe; border-color: #cfc; }
        .info { background: #eef; border-color: #ccf; }
        .warning { background: #fff3cd; border-color: #ffeaa7; }
        pre { 
            background: #f8f9fa; 
            padding: 12px; 
            border-radius: 4px; 
            overflow-x: auto; 
            font-size: 13px;
            border: 1px solid #e9ecef;
            max-height: 400px;
        }
        button { 
            padding: 10px 20px; 
            margin: 8px 5px; 
            cursor: pointer; 
            border: none;
            border-radius: 4px;
            font-weight: 500;
            background: #007bff;
            color: white;
        }
        .product-item {
            background: #f9f9f9;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 12px;
            margin: 8px 0;
        }
        .product-item .name {
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }
        .product-item .spec {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .product-item .labels {
            color: #007bff;
            font-size: 12px;
            font-family: monospace;
        }
        .highlight {
            background: #fff3d4;
            padding: 2px 4px;
            border-radius: 3px;
        }
        h1 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
        h3 { color: #555; margin-top: 0; }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background: #f5f5f5;
            font-weight: bold;
        }
        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: bold;
        }
        .badge-success { background: #d4edda; color: #155724; }
        .badge-danger { background: #f8d7da; color: #721c24; }
        .badge-warning { background: #fff3cd; color: #856404; }
    </style>
</head>
<body>
    <h1>🔍 产品数据调试工具</h1>
    
    <div class="container">
        <div class="section info">
            <h3>📋 调试说明</h3>
            <p>此工具用于检查产品数据结构，特别是验证：</p>
            <ul>
                <li><strong>spec.productTypeRef</strong>：产品类型引用字段</li>
                <li><strong>metadata.labels['content.halo.run/product-type-ref']</strong>：产品类型引用标签</li>
                <li><strong>ProductReconciler</strong>：是否正确设置了标签</li>
            </ul>
        </div>
    </div>

    <div class="container">
        <h3>🏗️ 数据检查</h3>
        <div class="section">
            <button onclick="loadAllData()">🔄 加载所有数据</button>
            <button onclick="testSpecificProduct()">🎯 测试特定产品</button>
            <button onclick="checkReconcilerStatus()">⚙️ 检查Reconciler状态</button>
        </div>
        <div id="dataResult"></div>
    </div>

    <div class="container">
        <h3>🧪 过滤测试</h3>
        <div class="section">
            <input type="text" id="testProductTypeRef" placeholder="输入productTypeRef进行测试" style="width: 300px; padding: 8px; margin-right: 10px;">
            <button onclick="testFilter()">🔍 测试过滤</button>
        </div>
        <div id="filterResult"></div>
    </div>

    <script>
        let allProducts = [];
        let allProductTypes = [];
        
        // 加载所有数据
        async function loadAllData() {
            const resultDiv = document.getElementById('dataResult');
            
            try {
                resultDiv.innerHTML = '<div class="section info">🔄 正在加载所有产品和产品类型数据...</div>';
                
                // 并行加载产品和产品类型
                const [productsResponse, typesResponse] = await Promise.all([
                    fetch('/apis/content.halo.run/v1alpha1/products?page=1&size=100'),
                    fetch('/apis/content.halo.run/v1alpha1/product-types?page=1&size=100')
                ]);
                
                if (!productsResponse.ok || !typesResponse.ok) {
                    throw new Error(`API请求失败: Products(${productsResponse.status}), Types(${typesResponse.status})`);
                }
                
                const productsData = await productsResponse.json();
                const typesData = await typesResponse.json();
                
                allProducts = productsData.items || [];
                allProductTypes = typesData.items || [];
                
                // 分析数据
                let html = `
                    <div class="section success">
                        <h4>✅ 数据加载成功</h4>
                        <p><strong>产品总数：</strong> ${allProducts.length}</p>
                        <p><strong>产品类型总数：</strong> ${allProductTypes.length}</p>
                    </div>
                `;
                
                // 产品类型表格
                if (allProductTypes.length > 0) {
                    html += `
                        <div class="section info">
                            <h4>📋 产品类型列表</h4>
                            <table>
                                <thead>
                                    <tr>
                                        <th>名称 (metadata.name)</th>
                                        <th>显示名称</th>
                                        <th>描述</th>
                                    </tr>
                                </thead>
                                <tbody>
                    `;
                    
                    allProductTypes.forEach(type => {
                        html += `
                            <tr>
                                <td><code>${type.metadata.name}</code></td>
                                <td>${type.spec.displayName}</td>
                                <td>${type.spec.description || '无'}</td>
                            </tr>
                        `;
                    });
                    
                    html += '</tbody></table></div>';
                }
                
                // 产品详细分析
                if (allProducts.length > 0) {
                    html += `
                        <div class="section info">
                            <h4>🔍 产品详细分析</h4>
                    `;
                    
                    let correctLabelCount = 0;
                    let missingLabelCount = 0;
                    let mismatchLabelCount = 0;
                    
                    allProducts.forEach(product => {
                        const specTypeRef = product.spec.productTypeRef;
                        const labelTypeRef = product.metadata.labels?.['content.halo.run/product-type-ref'];
                        
                        let status = '';
                        let badgeClass = '';
                        
                        if (!labelTypeRef) {
                            status = '❌ 缺少标签';
                            badgeClass = 'badge-danger';
                            missingLabelCount++;
                        } else if (labelTypeRef === specTypeRef) {
                            status = '✅ 标签正确';
                            badgeClass = 'badge-success';
                            correctLabelCount++;
                        } else {
                            status = '⚠️ 标签不匹配';
                            badgeClass = 'badge-warning';
                            mismatchLabelCount++;
                        }
                        
                        html += `
                            <div class="product-item">
                                <div class="name">${product.spec.displayName} <span class="badge ${badgeClass}">${status}</span></div>
                                <div class="spec"><strong>spec.productTypeRef:</strong> <span class="highlight">${specTypeRef || '未设置'}</span></div>
                                <div class="labels"><strong>labels['content.halo.run/product-type-ref']:</strong> <span class="highlight">${labelTypeRef || '未设置'}</span></div>
                                <div class="spec"><strong>metadata.name:</strong> ${product.metadata.name}</div>
                                ${product.metadata.labels ? `<div class="labels"><strong>所有标签:</strong> ${JSON.stringify(product.metadata.labels)}</div>` : '<div class="labels"><strong>标签:</strong> 无</div>'}
                            </div>
                        `;
                    });
                    
                    html += `
                            <div style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 5px;">
                                <h5 style="margin: 0 0 10px 0;">📊 统计结果：</h5>
                                <p style="margin: 5px 0;"><span class="badge badge-success">✅ 标签正确: ${correctLabelCount}</span></p>
                                <p style="margin: 5px 0;"><span class="badge badge-danger">❌ 缺少标签: ${missingLabelCount}</span></p>
                                <p style="margin: 5px 0;"><span class="badge badge-warning">⚠️ 标签不匹配: ${mismatchLabelCount}</span></p>
                            </div>
                        </div>
                    `;
                } else {
                    html += '<div class="section warning"><h4>⚠️ 没有找到任何产品</h4></div>';
                }
                
                html += `
                    <div class="section">
                        <details>
                            <summary><strong>🔍 查看完整产品数据</strong></summary>
                            <pre>${JSON.stringify(allProducts, null, 2)}</pre>
                        </details>
                    </div>
                `;
                
                resultDiv.innerHTML = html;
                
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="section error">
                        <h4>❌ 数据加载失败</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 测试特定产品
        async function testSpecificProduct() {
            // 这里可以测试URL中提到的涤纶纱线产品
            const productTypeRef = '涤纶纱线';
            document.getElementById('testProductTypeRef').value = productTypeRef;
            await testFilter();
        }
        
        // 测试过滤功能
        async function testFilter() {
            const resultDiv = document.getElementById('filterResult');
            const productTypeRef = document.getElementById('testProductTypeRef').value.trim();
            
            if (!productTypeRef) {
                resultDiv.innerHTML = '<div class="section warning">⚠️ 请输入productTypeRef</div>';
                return;
            }
            
            try {
                resultDiv.innerHTML = '<div class="section info">🔍 正在测试过滤功能...</div>';
                
                // URL编码productTypeRef
                const encodedTypeRef = encodeURIComponent(productTypeRef);
                const apiUrl = `/apis/content.halo.run/v1alpha1/products?page=1&size=100&productTypeRef=${encodedTypeRef}`;
                
                console.log('Testing filter with URL:', apiUrl);
                
                const response = await fetch(apiUrl);
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }
                
                const data = await response.json();
                const filteredProducts = data.items || [];
                
                // 分析过滤结果
                let html = `
                    <div class="section ${filteredProducts.length > 0 ? 'success' : 'warning'}">
                        <h4>${filteredProducts.length > 0 ? '✅' : '⚠️'} 过滤测试结果</h4>
                        <p><strong>过滤条件：</strong> <code>productTypeRef=${productTypeRef}</code></p>
                        <p><strong>API URL：</strong> <code>${apiUrl}</code></p>
                        <p><strong>返回数量：</strong> ${filteredProducts.length}</p>
                `;
                
                if (filteredProducts.length > 0) {
                    html += '<h5>📋 过滤结果：</h5>';
                    
                    let correctCount = 0;
                    filteredProducts.forEach((product, index) => {
                        const specTypeRef = product.spec.productTypeRef;
                        const labelTypeRef = product.metadata.labels?.['content.halo.run/product-type-ref'];
                        const isCorrect = labelTypeRef === productTypeRef || specTypeRef === productTypeRef;
                        
                        if (isCorrect) correctCount++;
                        
                        html += `
                            <div class="product-item" style="border-color: ${isCorrect ? '#28a745' : '#dc3545'}">
                                <div class="name">
                                    ${product.spec.displayName} 
                                    <span class="badge ${isCorrect ? 'badge-success' : 'badge-danger'}">
                                        ${isCorrect ? '✅ 匹配' : '❌ 不匹配'}
                                    </span>
                                </div>
                                <div class="spec"><strong>spec.productTypeRef:</strong> ${specTypeRef}</div>
                                <div class="labels"><strong>label:</strong> ${labelTypeRef || '未设置'}</div>
                            </div>
                        `;
                    });
                    
                    if (correctCount !== filteredProducts.length) {
                        html += `
                            <div class="section error">
                                <h4>❌ 过滤功能有问题！</h4>
                                <p>返回了 ${filteredProducts.length - correctCount} 个不匹配的产品。</p>
                                <p>这说明过滤逻辑没有正确工作。</p>
                            </div>
                        `;
                    }
                } else {
                    html += '<p><em>没有找到符合条件的产品</em></p>';
                    
                    // 检查是否有匹配的产品但过滤失败
                    if (allProducts.length > 0) {
                        const shouldMatch = allProducts.filter(p => 
                            p.spec.productTypeRef === productTypeRef || 
                            p.metadata.labels?.['content.halo.run/product-type-ref'] === productTypeRef
                        );
                        
                        if (shouldMatch.length > 0) {
                            html += `
                                <div class="section error">
                                    <h4>❌ 过滤功能失效！</h4>
                                    <p>应该返回 ${shouldMatch.length} 个匹配的产品，但实际返回了 0 个。</p>
                                    <h5>应该匹配的产品：</h5>
                            `;
                            
                            shouldMatch.forEach(product => {
                                html += `
                                    <div class="product-item">
                                        <div class="name">${product.spec.displayName}</div>
                                        <div class="spec"><strong>spec.productTypeRef:</strong> ${product.spec.productTypeRef}</div>
                                        <div class="labels"><strong>label:</strong> ${product.metadata.labels?.['content.halo.run/product-type-ref'] || '未设置'}</div>
                                    </div>
                                `;
                            });
                            
                            html += '</div>';
                        }
                    }
                }
                
                html += `
                        <details style="margin-top: 10px;">
                            <summary>查看完整响应数据</summary>
                            <pre>${JSON.stringify(data, null, 2)}</pre>
                        </details>
                    </div>
                `;
                
                resultDiv.innerHTML = html;
                
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="section error">
                        <h4>❌ 过滤测试失败</h4>
                        <pre>${error.message}</pre>
                    </div>
                `;
            }
        }
        
        // 检查Reconciler状态
        async function checkReconcilerStatus() {
            const resultDiv = document.getElementById('dataResult');
            
            const html = `
                <div class="section info">
                    <h4>⚙️ ProductReconciler 检查</h4>
                    <p><strong>Reconciler功能：</strong></p>
                    <ul>
                        <li>监听Product资源的变更</li>
                        <li>自动设置 <code>metadata.labels['content.halo.run/product-type-ref']</code> 标签</li>
                        <li>标签值来自 <code>spec.productTypeRef</code> 字段</li>
                    </ul>
                    <p><strong>检查方法：</strong></p>
                    <ol>
                        <li>点击"加载所有数据"查看当前产品的标签状态</li>
                        <li>如果发现缺少标签，可能需要：
                            <ul>
                                <li>重启Halo服务以触发Reconciler</li>
                                <li>在控制台编辑并保存产品以触发更新</li>
                                <li>检查Reconciler是否正确注册</li>
                            </ul>
                        </li>
                    </ol>
                    <div style="background: #fff3d4; padding: 10px; border-radius: 5px; margin-top: 10px;">
                        <p><strong>💡 提示：</strong> 如果ProductReconciler工作正常，所有产品的标签都应该与spec.productTypeRef一致。</p>
                    </div>
                </div>
            `;
            
            resultDiv.innerHTML = html;
        }
        
        // 页面加载时自动运行
        window.onload = function() {
            loadAllData();
        };
    </script>
</body>
</html>